from kivy.app import App
from kivy.lang import Builder
from kivy.properties import ObjectProperty, ListProperty, \
    StringProperty, BooleanProperty
from kivy.uix.modalview import ModalView
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.actionbar import ActionBar

Builder.load_file('goblinoid/comments/commentmodal.kv')


class CommentBar(ActionBar):
    open_previous = BooleanProperty(False)


class CommentModal(ModalView):
    activity_service = ObjectProperty()
    comments = ListProperty()

    def on_open(self):
        self.comments = self.activity_service.get_comments()

    def on_comments(self, instance, comments):
        if len(comments) > 0:
            for comment in comments:
                cell = CommentModalCell(
                    comment=comment,
                    delegate=self)
                self.ids.comment_layout.add_widget(cell)

    def build_description_cell(self):
        description_cell = ActivityDescriptionCell(self.activity)
        self.ids.comment_layout.add_widget(description_cell)

    # TODO ask Jessica why user_comment.content changes after posting it
    def post_comment(self, comment):
        pump_service = App.get_running_app().pump_service
        user_comment = pump_service.pump.Comment(comment)
        cell = CommentModalCell(
            comment=user_comment,
            delegate=self)
        self.ids.comment_layout.add_widget(
            cell,
            len(self.ids.comment_layout.children))
        self.activity_service.add_comment(user_comment)
        App.get_running_app().dispatch_event('on_comment')

    def open_profile(self, profile_id):
        App.get_running_app().dispatch_event(
            'on_new_screen',
            class_name='profile',
            name=profile_id,
            profile_id=profile_id)
        self.dismiss()


class CommentModalCell(BoxLayout):
    comment = ObjectProperty()
    delegate = ObjectProperty()
    comment_text = StringProperty()
    author = ObjectProperty()

    def on_comment(self, instance, comment):
        text = unicode(comment.content)
        if comment.author is None:
            self.author = App.get_running_app().pump_service.pump.me
        else:
            self.author = comment.author

        self.comment_text = unicode(
            '[ref=author][color=86D4B1]{0}[/color][/ref] {1}'.format(
                unicode(self.author.username),
                text))

    def open_profile(self):
        self.delegate.open_profile(unicode(self.author))


class ActivityDescriptionCell(BoxLayout):
    activity = ObjectProperty(None)
    description = ObjectProperty(None)
    actor = ObjectProperty(None)

    def __init__(self, activity):
        super(ActivityDescriptionCell, self).__init__()
        self.activity = activity
        self.description = activity.content
        self.actor = activity.actor
